from openpyxl import load_workbook
from math import ceil
import sys
sys.path.append("..")
from functional.utils import SPLIT_FUNC_DICT, JOIN_STR_DICT
from traceback import format_exc

def first_author_func(args):
	try:
		workbook_file_name = args[0]
		output_file_name = args[1]
		sheet_name = args[2]
		row_from = args[3]
		row_to = args[4]
		data_cols = args[5]
		signal = args[6]
		signal.emit("启动一作提取任务\n开始加载EXCEL文件")

		wb = load_workbook(workbook_file_name)
		signal.emit("完成EXCEL文件加载\n开始提取一作")
		sh = wb[sheet_name]

		for data_col in data_cols:
			input_col = data_col[1]
			output_col = data_col[2]
			addr_type = data_col[3]
			split_func = SPLIT_FUNC_DICT[addr_type]
			if row_from > 1:
				sh.cell(row_from-1, output_col).value = data_col[0]

			length = row_to - row_from + 1
			step = ceil(length*0.1)
			for i in range(row_from, row_to+1):
				addr_str = sh.cell(i, input_col).value
				addr = split_func(addr_str)
				if len(addr) == 0:
					sh.cell(i, output_col).value = ""
				else:
					sh.cell(i, output_col).value = addr[0]

				cnt = i - row_from + 1
				if cnt % step == 0:
					signal.emit(f"{data_col[0]}: {cnt/length*100:.2f}%")


		signal.emit("完成一作提取\n开始写入结果")
		wb.save(output_file_name)
		signal.emit("完成结果写入")
	except Exception as e:
		signal = args[6]
		signal.emit(f"提取失败：{e}\n追踪信息：{format_exc()}")